/**
 * 
 */
package cc.rico.jms.topic.publisher;

import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cc.rico.jms.utils.ActiveMQConnectionUtils;

/**
 * @author rico 2016年8月2日
 *
 */
public class SimplePublisher {
	private static final Logger logger = LoggerFactory.getLogger(SimplePublisher.class);
	
	private TopicConnection connection;
	private TopicSession session;
	private MessageProducer producer;
	
	public SimplePublisher() {
		try {
			//TopicConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.223.137:61616");
			//connection = connectionFactory.createTopicConnection();
			connection = ActiveMQConnectionUtils.createTopicConnection();
			
			session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
			Topic topic = session.createTopic("topic1");
			producer = session.createPublisher(topic);
			producer.setDeliveryMode(DeliveryMode.PERSISTENT);
			
			connection.start();
			
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
	public synchronized void sendMessage(String msg) {
		try {
			Message message = session.createTextMessage(msg);
			producer.send(message);
			logger.info("##SimplePublisher.sendMessage.msg={}", msg);
			
		} catch (JMSException e) {
			e.printStackTrace();
		}  
	}
	
	public synchronized void close() {
		try {
			session.close();
			connection.close();
			
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
}
